package com.fengke.csc.action.sso;

import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.fengke.csc.action.BaseAction;
import com.fengke.csc.config.HostConfig;
import com.fengke.service.AgentProfileService;
import com.fengke.service.MailService;
import com.fengke.service.vo.AgentProfileVO;
import com.fengke.util.Constants;
import com.fengke.util.LoggerFactory;
import com.fengke.util.StringUtil;

public class SSOAction extends BaseAction {
	private static final long serialVersionUID = -2785359752856730957L;
	private Logger logger = LoggerFactory.getLogger(SSOAction.class);
	private AgentProfileService agentProfileService;
	private AgentProfileVO agentProfileVO;
	/**
	 * 如已登录，则跳转至backURL
	 * 反之，跳转至登录页面
	 */
	public String loginForm() {
		logger.debug("show loginForm...");
		HttpSession session = this.getSession(false);
		if(session != null) {
			agentProfileVO = (AgentProfileVO) session.getAttribute(Constants.SessionProfileName.CSC_PROFILE_NAME);
			if(agentProfileVO != null) {
				// 已登录
				this.setBackURL((String) session.getAttribute(Constants.BACK_URL));
				if(StringUtil.isEmpty(this.getBackURL())) {
					HostConfig hostConfig = (HostConfig) session.getServletContext().getAttribute("hostConfig");
					this.setBackURL(hostConfig.getPortalHost());
				}
				return Constants.ActionReturnName.LOGINED;
			}
		}
		return Constants.ActionReturnName.NO_LOGIN;
	}
	
	public String login() {
		// 参数校验
		preLogin();
		if(this.hasPageDangerMessage()) {
			return INPUT;
		}
		// 登录成功
		agentProfileVO.getAdminModel().setLoginDate(new Date());
		agentProfileVO.getAdminModel().setIsLocked(false);
		agentProfileVO.getAdminModel().setLoginFailureCount(0);
		agentProfileVO.getAdminModel().setLockedDate(null);
		agentProfileVO.getAdminModel().setModifyDate(new Date());
		try {
			agentProfileService.updateAgentProfileLoginSuccessInfo(agentProfileVO);
		} catch (Exception e) {
			logger.error("login updateAgentProfileLoginSuccessInfo Exception! agentProfileVO=" + agentProfileVO, e);
		}
		
		HttpSession session = this.getSession(true);
		session.setAttribute(Constants.SessionProfileName.CSC_PROFILE_NAME, agentProfileVO);
		this.setBackURL((String) session.getAttribute(Constants.BACK_URL));
		System.out.println(this.getBackURL());
		if(StringUtil.isEmpty(this.getBackURL())) {
			HostConfig hostConfig = (HostConfig) session.getServletContext().getAttribute("hostConfig");
			this.setBackURL(hostConfig.getPortalHost());
		}
		session.removeAttribute(Constants.BACK_URL);
		return Constants.ActionReturnName.SUCCESS;
	}
	
	public String logout() {
		HttpSession session = this.getSession(false);
		if(session != null) {
			@SuppressWarnings("unchecked")
			Enumeration<String> num = session.getAttributeNames();
			while(num.hasMoreElements()){
				String sessionName = num.nextElement();
				session.removeAttribute(sessionName);
			}
			session.invalidate();
		}
		return Constants.ActionReturnName.SUCCESS;
	}
	/**
	 * login参数校验
	 */
	private void preLogin() {
		if(agentProfileVO == null || agentProfileVO.getAdminModel() == null) {
			this.addPageDangerMessage("登录信息不能为空！");
			return;
		}
		if(StringUtil.isEmpty(agentProfileVO.getAdminModel().getUsername())) {
			this.addPageDangerMessage("登录名不能为空！");
			return;
		}
		if(StringUtil.isEmpty(agentProfileVO.getAdminModel().getPassword())) {
			this.addPageDangerMessage("登录密码不能为空!");
			return;
		}
		try {
			agentProfileVO = agentProfileService.researchAgentProfileByLoginInfo(agentProfileVO);
		} catch (Exception e) {
			logger.error("preLogin Exception! agentProfileVO=" + agentProfileVO);
		}
		if(agentProfileVO == null || agentProfileVO.getAdminModel() == null || agentProfileVO.getAdminModel().getId() == null) {
			try {
				agentProfileVO = agentProfileService.researchAgentProfileByUsername(agentProfileVO);
			} catch (Exception e) {
				logger.error("preLogin researchAgentProfileByUsername Exception! agentProfileVO=" + agentProfileVO, e);
			}
			if(agentProfileVO != null) {
				if(agentProfileVO.getAdminModel().getIsLocked() != null && !agentProfileVO.getAdminModel().getIsLocked()) {
					if(Constants.CSC_LOGIN_ERROR_TIMES > agentProfileVO.getAdminModel().getLoginFailureCount()) {
						agentProfileVO.getAdminModel().setLoginFailureCount(agentProfileVO.getAdminModel().getLoginFailureCount() + 1);
					}
					if(Constants.CSC_LOGIN_ERROR_TIMES <= agentProfileVO.getAdminModel().getLoginFailureCount()) {
						agentProfileVO.getAdminModel().setIsLocked(true);
						agentProfileVO.getAdminModel().setLockedDate(new Date());
					}
					agentProfileVO.getAdminModel().setModifyDate(new Date());
					try {
						agentProfileService.updateAgentProfileLoginFailureInfo(agentProfileVO);
					} catch (Exception e) {
						logger.error("login updateAgentProfileLoginSuccessInfo Exception! agentProfileVO=" + agentProfileVO, e);
					}
					
					this.addPageDangerMessage("用户名或密码不正确!已连续错误" + agentProfileVO.getAdminModel().getLoginFailureCount() + "次!");
				} else {
					this.addPageDangerMessage("账号锁定中，不能登录!");
				}
			} else {
				this.addPageDangerMessage("用户名或密码不正确!");
			}
			// agentProfileVO = null;
			return;
		}
		
		// 账户有效性校验
		if(agentProfileVO.getAdminModel().getIsEnabled() == null || !agentProfileVO.getAdminModel().getIsEnabled()) {
			// 账户无效
			this.addPageDangerMessage("账号未能审核通过，不能登录!");
			return;
		}
		// 账户是否锁定
		if(agentProfileVO.getAdminModel().getIsLocked() != null && agentProfileVO.getAdminModel().getIsLocked()) {
			Calendar now = Calendar.getInstance();
			now.add(Calendar.DAY_OF_MONTH, -1);
			if(now.getTime().before(agentProfileVO.getAdminModel().getLockedDate())) {
				// 账户被锁定
				this.addPageDangerMessage("账号锁定中，不能登录!");
				return;
			} else {
				// 24小时后解锁
			}
		}
	}

	public AgentProfileService getAgentProfileService() {
		return agentProfileService;
	}
	public void setAgentProfileService(AgentProfileService agentProfileService) {
		this.agentProfileService = agentProfileService;
	}
	public AgentProfileVO getAgentProfileVO() {
		return agentProfileVO;
	}
	public void setAgentProfileVO(AgentProfileVO agentProfileVO) {
		this.agentProfileVO = agentProfileVO;
	}
}
